#!/usr/bin/env python3
"""
Easy RWKV 发布脚本
"""

import os
import sys
import subprocess
import shutil
from pathlib import Path


def run_command(cmd, description):
    """运行命令并处理错误"""
    print(f"🔧 {description}...")
    try:
        result = subprocess.run(cmd, shell=True, check=True, capture_output=True, text=True)
        print(f"✅ {description} 完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ {description} 失败:")
        print(f"   错误: {e.stderr}")
        return False


def check_dependencies():
    """检查发布依赖"""
    print("🔍 检查发布依赖...")
    
    try:
        import build
        print("✅ build 已安装")
    except ImportError:
        print("❌ build 未安装，请运行: pip install build")
        return False
    
    try:
        import twine
        print("✅ twine 已安装")
    except ImportError:
        print("❌ twine 未安装，请运行: pip install twine")
        return False
    
    return True


def clean_build():
    """清理构建目录"""
    print("🧹 清理旧的构建文件...")
    
    dirs_to_clean = ["build", "dist", "*.egg-info"]
    for dir_pattern in dirs_to_clean:
        for path in Path(".").glob(dir_pattern):
            if path.is_dir():
                shutil.rmtree(path)
                print(f"  删除目录: {path}")
            elif path.is_file():
                path.unlink()
                print(f"  删除文件: {path}")


def build_package():
    """构建包"""
    return run_command("python -m build", "构建包")


def check_package():
    """检查包"""
    return run_command("twine check dist/*", "检查包")


def upload_to_test_pypi():
    """上传到测试 PyPI"""
    print("🚀 上传到测试 PyPI...")
    print("   请确保已配置 TestPyPI 账户和 token")
    cmd = "twine upload --repository testpypi dist/*"
    return run_command(cmd, "上传到测试 PyPI")


def upload_to_pypi():
    """上传到正式 PyPI"""
    print("🚀 上传到正式 PyPI...")
    print("   请确保已配置 PyPI 账户和 token")
    
    # 确认上传
    confirm = input("确认上传到正式 PyPI？这个操作不可撤销！(y/N): ")
    if confirm.lower() not in ['y', 'yes']:
        print("❌ 取消上传")
        return False
    
    cmd = "twine upload dist/*"
    return run_command(cmd, "上传到正式 PyPI")


def main():
    """主函数"""
    print("=" * 60)
    print("📦 Easy RWKV 发布工具")
    print("=" * 60)
    
    if not check_dependencies():
        sys.exit(1)
    
    print("\n选择操作:")
    print("1. 完整发布流程 (清理 -> 构建 -> 检查 -> 测试 PyPI)")
    print("2. 仅构建包")
    print("3. 上传到测试 PyPI")
    print("4. 上传到正式 PyPI")
    print("5. 清理构建文件")
    
    choice = input("\n请选择 (1-5): ").strip()
    
    if choice == "1":
        # 完整发布流程
        steps = [
            clean_build,
            build_package,
            check_package,
            upload_to_test_pypi
        ]
        
        for step in steps:
            if not step():
                print("❌ 发布流程失败")
                sys.exit(1)
        
        print("\n🎉 发布到测试 PyPI 完成！")
        print("请测试安装: pip install -i https://test.pypi.org/simple/ easy-rwkv")
        
    elif choice == "2":
        clean_build()
        if build_package() and check_package():
            print("🎉 包构建完成！")
    
    elif choice == "3":
        if upload_to_test_pypi():
            print("🎉 上传到测试 PyPI 完成！")
    
    elif choice == "4":
        if upload_to_pypi():
            print("🎉 上传到正式 PyPI 完成！")
    
    elif choice == "5":
        clean_build()
        print("🎉 清理完成！")
    
    else:
        print("❌ 无效选择")
        sys.exit(1)


if __name__ == "__main__":
    main()
